package com.bawei.car.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.bawei.car.domain.CarInfo;
import com.bawei.car.domain.CarResult;
import com.bawei.car.domain.contants.CarContants;
import com.bawei.car.domain.model.CarInfoModel;
import com.bawei.car.domain.model.CarProductModel;
import com.bawei.car.domain.response.ShopCarResponse;
import com.bawei.car.domain.response.ShopCarSkuChange;
import com.bawei.car.domain.response.SkuResponse;
import com.bawei.car.service.ShopCarService;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.redis.service.RedisService;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.system.domain.model.LoginUser;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.commons.lang.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bawei.car.mapper.ShopCarMapper;
import com.bawei.car.domain.ShopCar;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 张氏企业帝国商品总览Service业务层处理
 *
 * @author 张氏企业帝国老总
 * @date 2022-11-16
 */
@Service
public class ShopCarServiceImpl implements ShopCarService
{
    @Autowired
    private ShopCarMapper shopCarMapper;


    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisService redisService;

    @Autowired
    ProductInfoCache productInfoCache;

    @Override
    public ShopCarResponse info() {
        return null;
    }

    /**
     * 查询张氏企业帝国商品总览
     *
     * @param id 张氏企业帝国商品总览主键
     * @return 张氏企业帝国商品总览
     */
    @Override
    public ShopCar selectShopCarById(Long id)
    {
        return shopCarMapper.selectShopCarById(id);
    }

    /**
     * 查询张氏企业帝国商品总览列表
     *
     * @param shopCar 张氏企业帝国商品总览
     * @return 张氏企业帝国商品总览
     */
    @Override
    public List<ShopCar> selectShopCarList(ShopCar shopCar)
    {
        return shopCarMapper.selectShopCarList(shopCar);
    }

    /**
     * 新增张氏企业帝国商品总览
     *
     * @param shopCar 张氏企业帝国商品总览
     * @return 结果
     */
    @Override
    public int insertShopCar(ShopCar shopCar)
    {
//        shopCar.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
//        shopCar.setCreateTime(DateUtils.getNowDate());
//        return shopCarMapper.insertShopCar(shopCar);
        return 0;
    }

    /**
     * 修改张氏企业帝国商品总览
     *
     * @param shopCar 张氏企业帝国商品总览
     * @return 结果
     */
    @Override
    public int updateShopCar(ShopCar shopCar)
    {
//        shopCar.setUpdateTime(DateUtils.getNowDate());
//        return shopCarMapper.updateShopCar(shopCar);
        return 0;
    }

    /**
     * 批量删除张氏企业帝国商品总览
     *
     * @param ids 需要删除的张氏企业帝国商品总览主键
     * @return 结果
     */
    @Override
    public int deleteShopCarByIds(Long[] ids)
    {
        return shopCarMapper.deleteShopCarByIds(ids);
    }

    /**
     * 删除张氏企业帝国商品总览信息
     *
     * @param id 张氏企业帝国商品总览主键
     * @return 结果
     */
    @Override
    public int deleteShopCarById(Long id)
    {
        return shopCarMapper.deleteShopCarById(id);
    }

    /**
     * 添加购物车
     * @param shopCar
     * @return
     */
    @Override
    public void addShopCar(ShopCar shopCar) {
        //查找当前登录的用户id
        String userId = SecurityUtils.getStrUserId();
        //用户购物车 存储键
        String carKey = CarContants.getCarKey(userId);
        //商品规格id
        String productSkuId = String.valueOf(shopCar.getProductSkuId());

        CarProductModel carProductModel=
        redisService.getCacheMapValue(carKey,productSkuId);

        //购物车当中没有 这条商品记录
        if(carProductModel == null){
            ShopCar shopCar1 = ShopCar.buildCarInfo(shopCar);
            //数据库新增
            shopCar.setCreateBy(userId);
            ShopCar shopCar2 = ShopCar.addCarInfo(shopCar);
            this.shopCarMapper.insertShopCar(shopCar2);
            //更新缓存对象
            carProductModel= shopCar2.infoToModel();
        }else {
            //刷新商品数量
            carProductModel.setNumber(carProductModel.getNumber() + 1);
            //修改数据库
//            this.shopCarMapper.updateShopCar(shopCar);
            this.shopCarMapper.upNumberToShopCar(userId,productSkuId,carProductModel.getProductId(),carProductModel.getNumber());
        }
        //刷新redis缓存
        redisService.setCacheMapValue(carKey,productSkuId,carProductModel);

    }

    /**
     * 查询购物车数据
     * @return
     */
    @Override
    public ShopCarResponse findShopCar() {
        //查找当前登录的用户id
        String userId = SecurityUtils.getStrUserId();
        //用户购物车 存储键
        String carKey = CarContants.getCarKey(userId);

        //通过购物车的key 获取到redis当中hash转换为map
        Map<String, CarProductModel> carInfoModelMap = redisService.getCacheMap(carKey);
        //通过购物车的对象，获取到需要的sku的详细信息
        ArrayList<SkuResponse> shopCarResponses = new ArrayList<>();
        BigDecimal sumPrice =BigDecimal.ZERO;
        //循环遍历 carInfoModelMap productSkuId 为 键、 carInfoModel 为 值
        for (Map.Entry<String, CarProductModel> carInfoModel : carInfoModelMap.entrySet()) {
            String productSkuId = carInfoModel.getKey();

            CarProductModel carProductModel = carInfoModel.getValue();

            SkuResponse skuResponse = new SkuResponse();
            //获取 productId (商品id)
            Long productId = carProductModel.getProductId();
            //获取该商品的信息
            ProductDetailsResponse productDetailsResponse = productInfoCache.get(productId);
            //商品详情存放到返回对象
            skuResponse.setCarProductModel(carProductModel);
            // 计算小计 商品单价 购物车商品数量
            Long number = carProductModel.getNumber();
            List<MallProductSkuInfo> skuList = productDetailsResponse.getSkuList();
//            ArrayList<MallProductSkuInfo> mallProductSkuInfos = new ArrayList<>();
            MallProductSkuInfo mallProductSkuInfos = null;
            BigDecimal price = null;
            for (MallProductSkuInfo mallProductSkuInfo : skuList) {
                if(productSkuId.equals(String.valueOf(mallProductSkuInfo.getId()))){
                    price = mallProductSkuInfo.getPrice().multiply(new BigDecimal(number)).
                            setScale(2,BigDecimal.ROUND_HALF_DOWN);
//                    mallProductSkuInfos.add(mallProductSkuInfo);
                    mallProductSkuInfos=mallProductSkuInfo;
                break;
                }
            }

            skuResponse.setProductSkuInfo(mallProductSkuInfos);
//            productDetailsResponse.setSkuList(mallProductSkuInfos);
            skuResponse.setProductInfo(productDetailsResponse);
            skuResponse.setProductSkuId(Long.valueOf(productSkuId));
            skuResponse.setSumPrice(price);
            //判断是否为选中的sku,如果是则进行计算 =》购物车的总价
            if(carProductModel.getIsChecked()){
                sumPrice=sumPrice.add(price);
            }
            shopCarResponses.add(skuResponse);

        }
        // 总价放入购物车的对象
        CarInfoModel carInfoModel = new CarInfoModel();
        carInfoModel.setSumPrice(sumPrice);

        ShopCarResponse shopCarResponse = new ShopCarResponse();
        shopCarResponse.setProductList(shopCarResponses);
        shopCarResponse.setCarInfoModel(carInfoModel);
        return shopCarResponse;
    }

    /**
     * 修改数量
     * @param shopCar
     */
    @Override
    public void updateNumber(@RequestBody ShopCar shopCar){
        //查找当前登录的用户id
        String userId = SecurityUtils.getStrUserId();
        //用户购物车 存储键
        String carKey = CarContants.getCarKey(userId);
        //获取token
        CarProductModel carProductModel=
                redisService.getCacheMapValue(carKey,String.valueOf(shopCar.getProductSkuId()));
        //修改数量
        carProductModel.setNumber(shopCar.getNumber());
        //刷新redis缓存
        redisService.setCacheMapValue(carKey,String.valueOf(shopCar.getProductSkuId()),carProductModel);
        //修改数据库
        this.shopCarMapper.upNumberToShopCar(userId,String.valueOf(shopCar.getProductSkuId()),shopCar.getProductId(),shopCar.getNumber());

    }

    /**
     * 修改选中状态
     * @param shopCar
     */
    @Override
    public void upChecked(ShopCar shopCar){

        //改变当前状态
        //查找当前登录的用户id
        String userId = SecurityUtils.getStrUserId();
        //用户购物车 存储键
        String carKey = CarContants.getCarKey(userId);
        //获取缓存
        CarProductModel carProductModel=
                redisService.getCacheMapValue(carKey,String.valueOf(shopCar.getProductSkuId()));
        // 修改数据库状态
        ShopCar shopCar1 = ShopCar.addCarInfo(shopCar);
        shopCar1.setCreateBy(userId);
        this.shopCarMapper.upChecked(shopCar1);

        //修改状态
        CarProductModel carProductModel1 = shopCar.infoToModelAndIsChecked();

        //刷新缓存
        redisService.setCacheMapValue(carKey,String.valueOf(shopCar.getProductSkuId()),carProductModel1);

    }

    /**
     * skuid修改
     * @param carSkuChange
     */
    @Override
    public void skuChange(@RequestBody ShopCarSkuChange carSkuChange){
        //查找当前登录的用户id
        String userId = SecurityUtils.getStrUserId();
        //用户购物车 存储键
        String carKey = CarContants.getCarKey(userId);
        //获取改变前的sku信息
        CarProductModel carProductModel=
                redisService.getCacheMapValue(carKey,String.valueOf(carSkuChange.getOldProductSkuId()));
        //获取改变后的sku信息
        CarProductModel carProductModel1=
                redisService.getCacheMapValue(carKey,String.valueOf(carSkuChange.getNewProductSkuId()));
        CarProductModel carProductModel2 = new CarProductModel();
        //修改数据库数据
        ShopCar shopCar = new ShopCar();
        shopCar.setProductSkuId(carSkuChange.getNewProductSkuId());
        shopCar.setCreateBy(userId);
        shopCar.setProductId(carSkuChange.getOldProductSkuId());

        //判断改变前后的sku是否冲突
        if(carProductModel1 == null) {
            /**
             * 未冲突
             */
            //为新的sku赋值
            String flag = carProductModel.getIsChecked()==true ? "true" : "false";
            carProductModel2.setNumber(carProductModel.getNumber());
            carProductModel2.setProductId(carProductModel.getProductId());
            carProductModel2.setIsChecked(flag);
            //修改数控库信息
            this.shopCarMapper.upSkuShopCar(shopCar);

            //删除旧数据
            redisService.deleteCacheMapValue(carKey,String.valueOf(carSkuChange.getOldProductSkuId()));
            redisService.setCacheMapValue(carKey,String.valueOf(carSkuChange.getNewProductSkuId()),carProductModel2);
        }else {

            //冲突
            carProductModel1.setNumber(carProductModel.getNumber()+carProductModel1.getNumber());

            //修改数据库数量
            shopCar.setNumber(carProductModel1.getNumber());
            //修改数据库信息
            this.shopCarMapper.deleteShopCarByShopCar(shopCar);
            this.shopCarMapper.upSkuAndNumberShopCar(shopCar);

            /**
             * 修改redis缓存
             */
            // 删除旧的sku
            redisService.deleteCacheMapValue(carKey,String.valueOf(carSkuChange.getOldProductSkuId()));
            // 刷新redis缓存
            redisService.setCacheMapValue(carKey,String.valueOf(carSkuChange.getNewProductSkuId()),carProductModel1);

        }
    }
}
